package com.qibao.toolkit.exception.strategy.impl;

import com.qibao.toolkit.exception.strategy.AbstractExceptionHandleStrategy;
import com.qibao.toolkit.exception.strategy.BaseExceptionHandleStrategyAware;
import com.qibao.toolkit.exception.strategy.ExceptionHandleType;
import com.qibao.toolkit.exception.strategy.properties.ExceptionProperties;
import com.qibao.toolkit.web.ResponseModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 默认的异常处理策略
 *
 * @author wangcheng
 * @version $Id: DefaultExceptionHandleStrategy.java, v0.1 2018/9/26 10:14 wangcheng Exp $$
 */
@ExceptionHandleType(value = {Throwable.class}, name = "defaultExceptionHandleStrategy")
public class DefaultExceptionHandleStrategy extends AbstractExceptionHandleStrategy implements
        BaseExceptionHandleStrategyAware {

    private static final Logger logger = LoggerFactory.getLogger(DefaultExceptionHandleStrategy.class);

    private ExceptionProperties exceptionProperties;

    public DefaultExceptionHandleStrategy(ExceptionProperties exceptionProperties) {
        this.exceptionProperties = exceptionProperties;
    }


    @Override
    public ResponseModel doHandle(Throwable throwable) {
        if (exceptionProperties.getPrintStackTrace()) {
            logger.error("程序出现异常",throwable);
            StackTraceElement[] stackTrace = throwable.getStackTrace();
            for (int i = 0; i < stackTrace.length; i++) {
                StackTraceElement ste = stackTrace[i];
                if (StringUtils.startsWithIgnoreCase(ste.getClassName(), exceptionProperties.getBbdPackage())) {
                    StringBuilder builder = new StringBuilder("\n");
                    builder.append("\texception class ---------->").append(throwable.getClass().getName()).append("\n")
                            .append("\texception message ---------->").append(throwable.getMessage()).append("\n")
                            .append("\tclassName ---------->").append(ste.getClassName()).append("\n")
                            .append("\tmethodName ----------> ").append(ste.getMethodName()).append("\n")
                            .append("\tlineNumber ----------> ").append(ste.getLineNumber()).append("\n")
                            .append("\tisNativeMethod ----------> ").append(ste.isNativeMethod()).append("\n");
                    //记录出现异常的位置
                    logger.error(builder.toString());
                    break;
                }
            }
        }
        return ResponseModel.ERROR(exceptionProperties.getErrorMessage());
    }


}
